package com.flyou.ccnucenter.utils;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ThumbnailUtils;
import android.util.Log;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.ref.SoftReference;

public class BitmapTool {

    ThumbnailUtils thumbnailUtils;

    public Bitmap getBitmap(String filePath) {

        BitmapFactory.Options ops = new BitmapFactory.Options();
        ops.inJustDecodeBounds = true;

        int width = ops.outWidth;
        int height = ops.outHeight;

        int xScale = width / 150;
        int yScale = height / 150;

        ops.inSampleSize = xScale > yScale ? xScale : yScale;

        ops.inJustDecodeBounds = false;

        MyBitmap2 bit = new MyBitmap2();
        bit.MyBitamp(BitmapFactory.decodeFile(filePath, ops));

        return bit.get();

    }

    /****************************************************************************/
    /****************************************************************************/
    /**
     * ************************************************************************
     */

    public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidht = ((float) w / width);
        float scaleHeight = ((float) h / height);
        matrix.postScale(scaleWidht, scaleHeight);
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
                matrix, true);
        return newbmp;
    }

    public static Bitmap getImageThumbnail(String imagePath, int width,
                                           int height) {
        Bitmap bitmap = getCompressedBitmapFromPath(imagePath, width, height);
//        bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
//                ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
        return bitmap;
    }

    private static Bitmap getCompressedBitmapFromPath(String imagePath,
                                                      int width, int height) {

        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        bitmap = BitmapFactory.decodeFile(imagePath, options);
        options.inJustDecodeBounds = false;
        int h = options.outHeight;
        int w = options.outWidth;
        int beWidth = 0;
        int beHeight = 0;
        if (width != 0) {
            beWidth = w / width;
        }
        if (height != 0) {
            beHeight = h / height;
        }
        int be = 1;
        if (height == 0) {
            be = beWidth;
        } else if (width == 0) {
            be = beHeight;
        } else {
            if (beWidth < beHeight) {
                be = beWidth;
            } else {
                be = beHeight;
            }
        }
        if (be <= 0) {
            be = 1;
        }
        options.inSampleSize = be;
        options.inPreferredConfig= Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;
                bitmap = BitmapFactory.decodeFile(imagePath, options);
        int size = bitmap.getByteCount() / 1024;
        MyLog.d(be+":哈哈哈哈哈"+size);
        while (size >= 512) {
            be++;

            options.inSampleSize = be;
            bitmap = BitmapFactory.decodeFile(imagePath, options);
            size = bitmap.getByteCount() / 1024;
            MyLog.d(be+":哈哈哈哈哈while"+size);
        }
        return bitmap;
    }

    public static String getPathFromBitmap(String imagePath, int width,
                                           int height) {

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
        options.inJustDecodeBounds = false;
        int h = options.outHeight;
        int w = options.outWidth;

        if (width == 0) {
            if (h < height) {
                return imagePath;
            }
        } else if (height == 0) {
            if (w < width) {
                return imagePath;
            }
        }

        Bitmap bmp = getCompressedBitmapFromPath(imagePath, width, height);

        return saveBitmapToSdcard(bmp);
    }

    /**
     * 将bitmap保存到内存卡中
     *
     * @param bitmap
     */
    @SuppressWarnings("finally")
    private static String saveBitmapToSdcard(Bitmap bitmap) {
        String path = null;
        File root = new File(SDCardUtils.getSDCardPath()+File.separator+"henucenter");
        if (!root.exists()) {// 如果目录不存在就创建目录
            root.mkdirs();
        }
        String name = System.currentTimeMillis() + ".jpg";
        File file = new File(root, name);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            if (bitmap != null) {
                /*
                 * 三个参数的含义分别是： 1.保存图片的格式
				 * 2.标识图片质量0~100.质量越小压缩的越小（这里设置100标识不压缩）。另外如果图片是png格式
				 * ，压缩是无损的，将忽略此参数（设置无效） 3.向OutputStream写入图片数据
				 */
                bitmap.compress(CompressFormat.JPEG, 100, out);
                out.flush();
                path = file.getAbsolutePath();
            }
        } catch (Exception e) {
            e.printStackTrace();
            path = null;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (final Exception e) {
                e.printStackTrace();
                path = null;
            }

            return path;
        }

    }

    // 质量压缩法
    public static String compressImage(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return null;
        }
        Bitmap image = BitmapFactory.decodeFile(path);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        Log.e("baos", baos.toByteArray().length / 1024 + "");
        if (baos.toByteArray().length / 1024 < 512) {
            return path;
        }
        int options = 100;
        while (baos.toByteArray().length / 1024 >= 512) { // 循环判断如果压缩后图片是否大于512kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            options -= 10;// 每次都减少10
            image.compress(CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片

        return saveBitmapToSdcard(bitmap);
    }

    /****************************************************************************/
    /****************************************************************************/
    /**
     * ************************************************************************
     */

    class MyBitmap2 {
        private SoftReference<Bitmap> sf;

        public void MyBitamp(Bitmap bm) {
            sf = new SoftReference<Bitmap>(bm);
        }

        public Bitmap get() {
            return sf.get();
        }

    }
    /*
    * 压缩图片上传
    * @param picPath
    * @return
    */
    public static   File compressPicture(String picPath,String userId) {
        int maxWidth = 480, maxHeight = 800;  //设置新图片的大小

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap image = BitmapFactory.decodeFile(picPath, options);
        double ratio = 1D;
        if (maxWidth > 0 && maxHeight <= 0) {
            // 限定宽度，高度不做限制
            ratio = Math.ceil(options.outWidth / maxWidth);
        } else if (maxHeight > 0 && maxWidth <= 0) {
            // 限定高度，不限制宽度
            ratio = Math.ceil(options.outHeight / maxHeight);
        } else if (maxWidth > 0 && maxHeight > 0) {
            // 高度和宽度都做了限制，这时候我们计算在这个限制内能容纳的最大的图片尺寸，不会使图片变形
            double _widthRatio = Math.ceil(options.outWidth / maxWidth);
            double _heightRatio = (double) Math.ceil(options.outHeight / maxHeight);
            ratio = _widthRatio > _heightRatio ? _widthRatio : _heightRatio;
        }
        if (ratio > 1)
            options.inSampleSize = (int) ratio;
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        image = BitmapFactory.decodeFile(picPath, options);
        //保存入sdCard

        File root = new File(SDCardUtils.getSDCardPath() + File.separator + "henucenter");
        if (!root.exists()) {
            root.mkdirs();
        }
        File file;
        try {
            String name = userId+System.currentTimeMillis() + ".jpg";
            file = new File(root, name);
            FileOutputStream out = new FileOutputStream(file);
            if (image.compress(CompressFormat.JPEG, 100, out)) {
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new File(picPath);
        } finally {
            if (image != null && !image.isRecycled()) {
                image.recycle();
            }
        }
        return file;
    }





    private static String compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while ( baos.toByteArray().length / 1024>400) {	//循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return saveBitmapToSdcard(bitmap);
    }


    public static String getimagePath(String srcPath) {
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空

        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
        return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
    }


    public static String comp(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        if( baos.toByteArray().length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        return compressImage(bitmap);//压缩好比例大小后再进行质量压缩
    }
}